package com.walnut.lom_system.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.walnut.lom_system.common.exception.CaptchaException;
import com.walnut.lom_system.common.lang.Const;
import com.walnut.lom_system.common.securtiy.MyLoginFailureHandler;
import com.walnut.lom_system.common.util.JsonParamUtil;
import com.walnut.lom_system.common.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 验证码校验的过滤器，在用户名密码校验之前
 * @author walnut
 * @version 1.0
 * @date 2021/11/7 8:08 下午
 */
@Component
@Slf4j
public class CaptchaFilter extends OncePerRequestFilter {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MyLoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {



        String url = request.getRequestURI();
        log.info("请求接口: "+request.getMethod().toUpperCase() +" : "+ url);

//        if ("/captcha".equals(url) && "POST".equals(request.getMethod())) {
////            response.setHeader("Access-Control-Allow-Origin", "*");
////            response.setHeader("Access-Control-Allow-Headers","*");
////            response.setHeader("Access-Control-Allow-Methods","*");
////            response.setHeader("Access-Control-Allow-Credentials","true");
////            response.setHeader("Access-Control-Max-Age","3600");
//        }
        boolean login = "/login".equals(url) && "POST".equals(request.getMethod());
        boolean register = "/user/register".equals(url) && "POST".equals(request.getMethod());
        if ( login || register ) {
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            response.setHeader("Access-Control-Allow-Headers","*");
//            response.setHeader("Access-Control-Allow-Methods","*");
//            response.setHeader("Access-Control-Allow-Credentials","true");
//            response.setHeader("Access-Control-Max-Age","3600");
            try {
                // 校验验证码
                log.info("⬇   验证码校验  ⬇");
                validate(request);
                log.info("⬆ 验证码校验结束 ⬆");
            } catch (CaptchaException e) {
                // 跳转到认证失败处理器
                log.error("❌验证码出错❌");
                loginFailureHandler.onAuthenticationFailure(request, response, e);
//                throw e;
                return;
            }

        }
        // 继续执行Filter
        filterChain.doFilter(request, response);
    }

    /**
     * 校验验证码
     *
     * @param request
     */
    private void validate(HttpServletRequest request) throws CaptchaException {

        log.info(" :: sessionINFO IN CaptchaFilter" + request.getSession(false));
        String input = null;
        if ("/user/register".equals(request.getRequestURI()) && "POST".equals(request.getMethod())) {
            String jsonParam = JsonParamUtil.getJsonParam(request);
            System.out.println(jsonParam);
            input = JSONObject.parseObject(jsonParam).getString("code");
            log.info("input: " + input);
            request.getSession().setAttribute("form",jsonParam);

        } else {
            input = request.getParameter("code");
            log.info("input: " + input);
            log.info("input: " + request.getParameter("password"));
        }

        //获取系统中的验证码
        String code = (String) request.getSession().getAttribute(Const.CAPTCHA_KEY);

        //获取系统中验证码创建时间
        Long time = (Long) request.getSession().getAttribute(Const.CAPTCHA_KEY+"Time" );

        request.getSession().removeAttribute(Const.CAPTCHA_KEY);
        request.getSession().removeAttribute(Const.CAPTCHA_KEY+"Time");

        //TODO 删除固定验证码
        if ("0".equals(input)){
            log.warn( "✅验证码固定通过");
            return;
        }


        if (code == null || time-System.currentTimeMillis() >= 3*60*1000 || !code.equals(input)) {
            log.warn( "❌验证码验证出错");
            //TODO 测试，需删除LOG

            if (code == null) {
                log.warn( "❌验证码不存在");
            } else{
                log.warn( "验证码匹配结果=>" + (code.equals(input)?"成功":"失败"));
                log.warn( "生成验证码" +code);
                log.warn( "输入验证码" +input);
                log.warn( "是否过期=>" +((time-System.currentTimeMillis() >= 3*60*1000)?"有效":"过期"));
            }
            //错误
            throw new CaptchaException("验证码错误,请刷新验证码");
        }


    }

}

